package com.orangelife.mobile.pay.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.jump.PayJumper;
import com.common.jump.WebJumper;
import com.common.sp.PaySp;
import com.common.sp.UserSp;
import com.common.util.CommonHttpBiz;
import com.curry.android.http.HttpUtil;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DecimalUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.FastJsonTools;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.MoneyUtil;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.datatrack.DataTrack;
import com.orangelife.mobile.app.application.ExitApplication;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.confirmOrder.entity.PaidInfo;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.individual.activity.BalanceRechargeActivity;
import com.orangelife.mobile.pay.biz.PayHttpBiz;
import com.orangelife.mobile.pay.biz.PayPwdHttpBiz;
import com.orangelife.mobile.pay.interfaze.IPayCallBack;
import com.orangelife.mobile.pay.interfaze.IPayManage;
import com.orangelife.mobile.pay.biz.PaymentModule;
import com.orangelife.mobile.pay.biz.ThridPayKeyRequest;
import com.orangelife.mobile.pay.view.PayPwdDialog;
import com.orangelife.mobile.property.biz.PropertyHttpBiz;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.tencent.mm.sdk.constants.ConstantsAPI;
import com.tencent.mm.sdk.modelbase.BaseResp;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 第三方支付界面
 *
 * @author cfr
 */
public class UsersPaidActivity extends ThridPayKeyRequest {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.tvPaid)
    TextView tvPaid;/*支付按钮*/

    @Bind(R.id.tvOrderTotalPrice)
    TextView tvOrderTotalPrice;
    @Bind(R.id.tvTotalPrice)
    TextView tvTotalPrice;

    @Bind(R.id.tvOrderInfoText)
    TextView tvOrderInfoText;/*订单信息*/

    @Bind(R.id.tvPropertyWalletPrice)
    TextView tvPropertyWalletPrice;/*物业费钱包余额*/

    @Bind(R.id.tvWalletPrice)
    TextView tvWalletPrice;/*钱包余额*/
    @Bind(R.id.tvWalletSurplus)
    TextView tvWalletSurplus;/*还需*/
    @Bind(R.id.tvRemaindMoney)
    TextView tvRemaindMoney;/*钱包支付後剩余金额*/
//    private TextView tvCreditSurplus;


    @Bind(R.id.btnRechargeWallet)
    Button btnRechargeWallet;/*充值钱包按钮*/

    @Bind(R.id.btnRechargePropertyWallet)
    Button btnRechargePropertyWallet;/*充值物业费钱包按钮*/

    /** 钱包支付 */
    @Bind(R.id.rlBalancePaidPrice)
    RelativeLayout rlBalancePaidPrice;
    /** 支付宝支付 */
    @Bind(R.id.rlApilayPaidPrice)
    RelativeLayout rlApilayPaidPrice;
    /** 银联支付 */
    @Bind(R.id.rlRepeatedlyPaidPrice)
    RelativeLayout rlRepeatedPaidPrice;
    /** 微信支付 */
    @Bind(R.id.rlWeChatPaidPrice)
    RelativeLayout rlWeChatPaidPrice;
    //rlCreditPaidPrice R.id.rlCreditPaidPrice;
    @Bind(R.id.rlPropertyWallet)
    RelativeLayout rlPropertyWallet;

    @Bind(R.id.ibChooseBalance)
    ImageView ibChooseBalance;/*选择钱包*/
    @Bind(R.id.ibChooseApilay)
    ImageView ibChooseApilay;/*选择支付宝*/
    //    @Bind(R.id.ibChooseCredit)
//    ImageView ibChooseCredit;
    @Bind(R.id.ibChooseRepeated)
    ImageView ibChooseRepeated;/*选择银联*/
    @Bind(R.id.ibChooseWeChat)
    ImageView ibChooseWeChat;/*选择微信*/
    @Bind(R.id.ibChoosePropertyWallet)
    ImageView ibChoosePropertyWallet;

    private boolean isWalletChoose;
    private boolean isApilayChoose;
    private boolean isCreditChoose;
    private boolean isRepeatedChoose;
    private boolean isWeChatChoose;
    private boolean isPropertyWalletChoose;

    private static final int WALLET_BALANCE = 3;
    private static final int VOCHER_CANCEL = 4;
    private static final int CREDIT_PAID = 5;
    private static final int REPERT_KEY = 6;
    private static final int PAID_METHOD = 7;
    private String totalCost;/*应付总额*/
    private String walletBalance;
    private String outtradeno;/*订单支付流水号*/
    private String orderID;
    private String mOrderType;
    private String totalPrice;
    private String orderInfo;
    private String repairID;
    private String serviceOrderID;
    private String phone;
    private String status;
    private String points;/*积分*/
    private String type;
    private int feeType;

    private String balance;/*钱包余额*/

    private Boolean orderList;
    private PaidInfo paidInfo;
    private ArrayList<String> products;
    private String productID;
    private final String MODULE_NAME = "/payOdr";
    private String paymentModuleCode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_users_paid);
        ButterKnife.bind(this);
        getIntentInfo();
        getIntentInfo2();
        paidInfo = new PaidInfo();
        if (TextUtils.isEmpty(productID))
            delShopCartItem();
        if (products != null) {
            delSelectedShopCartGoods();
        }
        setTitle();
    }

    @Override
    protected void onResume() {
        super.onResume();
        /*在界面重新亮起的时候,刷新其余额*/
        if (isPropertyWalletChoose) {/*若支持物业缴费钱包支付*/
            requestPropertyWalletMoney();
        } else if (isWalletChoose) {
            requestWalletPrice();
        }
        requestPayPwdInfo();
    }

    private void setTitle() {
        tvTitle.setText(getResources().getString(R.string.paid));
    }

    private void getIntentInfo() {
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        productID = bundle.getString("productID");
        products = bundle.getStringArrayList("productsID");
        orderInfo = bundle.getString("orderInfo");
        totalPrice = bundle.getString("totalPrice");
        totalCost = bundle.getString("totalCost");
        walletBalance = getIntent().getExtras().getString("money");

        paymentModuleCode = bundle.getString(PaymentModule.PAID_METHOD);
        requestPaidMethod(paymentModuleCode);

        tvOrderInfoText.setText(orderInfo);
        tvOrderTotalPrice.setText(MoneyUtil.handleMoney(totalPrice));
        tvTotalPrice.setText(MoneyUtil.handleMoney(totalPrice));

        setWalletText();
    }

    private void getIntentInfo2() {
        outtradeno = getIntent().getExtras().getString("outtradeno");
        orderID = getIntent().getExtras().getString("orderID");
        mOrderType = getIntent().getExtras().getString("orderType");
        type = getIntent().getExtras().getString("type");
        feeType = getIntent().getExtras().getInt("feeType");
        repairID = getIntent().getExtras().getString("repairID");
        serviceOrderID = getIntent().getExtras().getString("serviceOrderID");
        orderList = getIntent().getExtras().getBoolean("orderList");
        phone = getIntent().getExtras().getString("phone");
        status = getIntent().getExtras().getString("status");
        points = getIntent().getExtras().getString("points");
    }

    /** 数据采集体不要删除 */
    public Map<String, Object> getDataTrack() {
        Map<String, Object> map = new HashMap<>();
        map.put("UI_HOST", DataTrack.APP_NAME);
        map.put("UI_PATH", MODULE_NAME);
        map.put("OdrType", orderInfo);
        return map;
    }

    private String statusCode;
    private String statusInfo;

    /** 请求支付密码信息 */
    private void requestPayPwdInfo() {
        showDialog();
        PayPwdHttpBiz.getPayPwdInfo(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                Map<String, Object> map = CommonHttpBiz.handleEntity(jsonObject, false);
                if (map != null) {
                    statusCode = String.valueOf(map.get("stateCode"));
                    statusInfo = String.valueOf(map.get("stateInfo"));
                    //useCount
                    //freezeTime
                }
            }
        });
    }

    /** 根据订单类型(旧根据支付类型)请求支持的支付方式 */
    private void requestPaidMethod(String paymentModuleCode) {
        PayHttpBiz.getPaidMethod(paymentModuleCode, mOrderType, handler, PAID_METHOD);
    }

    /** 请求物业费钱包余额信息 */
    private void requestPropertyWalletMoney() {
        PayHttpBiz.getPropertyWalletMoney(new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                Map<String, Object> map = CommonHttpBiz.handleEntity(jsonObject);
                if (map != null) {
                    String money = String.valueOf(map.get("money"));
                    setPropertyWalletInfo(money);
                }
            }
        });
    }

    /** 获取钱包总额信息 */
    private void requestWalletPrice() {
        showDialog();
        String url = Constant.URL_MY_WALLET;
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, null, handler, WALLET_BALANCE, HttpUtil.ACTION_URI);
    }

    /** 支付成功之后，更新物业缴费账单的状态，未支付转为支付中 */
    private void requestUpdatePropertyOrderStatus() {
        if (orderID != null && PaymentModule.mode[4].equals(paymentModuleCode)) {
            PropertyHttpBiz.updatePayBill(orderID, new VolleyHttpUtil.ResponseCallBack() {
                @Override
                public void handleResponse(JSONObject response, int errCode) {
                    OrangeErrorHandler.getInstance().isSuccess(response);
                }
            });
        }
    }

    /** 使用钱包支付(PayHttpBiz已经有了) */
    private void requestPayWithWallet() {
        if (Double.parseDouble(balance) < Double.parseDouble(totalCost)) {
            closeDialog();
            ToastHelper.getInstance()._toast("钱包余额不足，请充值。");
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("payOrderID", outtradeno);
            JSONRequest.getInstance().sendRequest(JSONRequest.GET, Constant.URL_BALANCE_PAID, map, handler, 0, HttpUtil.ACTION_URI);
        }
    }

    /** 使用物业缴费钱包支付 */
    private void requestPayWithPropertyWallet() {
        PayHttpBiz.payWithPropertyWallet(outtradeno, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                closeDialog();
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    ExitApplication.getInstance().addMainActivity(UsersPaidActivity.this);
                    ToastHelper.getInstance()._toast("支付成功");
                    disablePayButton();/*禁用支付按钮*/
                    requestPropertyWalletMoney();/*刷新余额*/
                    skipResult(0);
                } else {
                    skipResult(2);
                }
                requestUpdatePropertyOrderStatus();
            }
        });
    }

    /** 获取连连支付信息 */
    private void requestPayWithUnionPay() {
        String url = Constant.URL_REPEAT;
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, null, handler, REPERT_KEY, HttpUtil.ACTION_URI);
    }

    /** 根据钱包余额是否足够支付订单，展示相应数据 */
    private void setWalletText() {
        balance = walletBalance;
        if (balance != null) {
            if (Double.parseDouble(balance) < Double.parseDouble(totalCost)) {/*应付金额>钱包余额*/
                btnRechargeWallet.setVisibility(View.VISIBLE);/*显示充值按钮*/
                ibChooseBalance.setVisibility(View.GONE);
                tvWalletSurplus.setText("还需");
                tvRemaindMoney.setText(DecimalUtil.subtract(totalCost, balance));
            } else {
                tvWalletSurplus.setText("支付完剩余");
                btnRechargeWallet.setVisibility(View.GONE);
                ibChooseBalance.setVisibility(View.VISIBLE);
                tvRemaindMoney.setText(DecimalUtil.subtract(balance, totalCost));
            }
            tvWalletPrice.setText(balance);
        } else {/*请求失败,重新获取*/
            requestWalletPrice();
        }
    }

    /** 设置物业缴费钱包金额信息 */
    private void setPropertyWalletInfo(String propertyBalance) {/*物业缴费钱包的余额*/
        if (propertyBalance != null && (Double.parseDouble(propertyBalance) < Double.parseDouble(totalCost))) {/*应付金额>钱包余额*/
            btnRechargePropertyWallet.setVisibility(View.VISIBLE);/*显示充值按钮*/
            ibChoosePropertyWallet.setVisibility(View.GONE);
        } else {
            btnRechargePropertyWallet.setVisibility(View.GONE);
            ibChoosePropertyWallet.setVisibility(View.VISIBLE);
        }
        tvPropertyWalletPrice.setText(Constant.RMB_FLAG + MoneyUtil.handleMoney(propertyBalance));
    }

    /** 跳转到物业缴费钱包充值界面 */
    private void jumpToPropertyWalletRecharge() {
        WebJumper.jumpToPropertyWalletRecharge(UsersPaidActivity.this);
        finish();/*由于会重新返回当前界面,所以需要先关闭此界面*/
    }

    /** 跳转到钱包充值界面 */
    private void jumpToRechargeWallet() {
        Intent intent = new Intent(this, BalanceRechargeActivity.class);
        startActivityForResult(intent, 1);
    }

    /** 是否需要输入支付密码 */
    private void checkPayPwd() {
        if (isWalletChoose || isPropertyWalletChoose) {//钱包需要支付密码
            if ("0".equals(statusCode)) {//已设置
                showPayPwd();
                PaySp.setNeverSetPayPwd(true);
            } else if ("2".equals(statusCode)) {//被冻结
                showFrozenDialog();
                PaySp.setNeverSetPayPwd(true);
            } else if ("1".equals(statusCode)) {
                setPaid();
            } else {
                ToastHelper.getInstance()._toast("获取支付密码状态失败,请稍后再试");
            }
        } else {//其他支付方式不需要
            setPaid();
        }
    }


    /** 支付密码弹出框 */
    private void showPayPwd() {
        final PayPwdDialog ppd = new PayPwdDialog(this, false);
        ppd.setOnValidatePayPwdListener(new PayPwdDialog.OnValidatePayPwdListener() {
            @Override
            public void onValidated(String statusCode, String statusInfo) {
                if ("0".equals(statusCode)) {//成功
                    ppd.dismiss();//执行原先的支付流程
                    setPaid();
                } else if ("2".equals(statusCode)) {//冻结
                    ppd.dismiss();//关闭密码框
                    UsersPaidActivity.this.statusInfo = statusInfo;
                    showFrozenDialog();//显示冻结框
                } else {//失败,设置标题
                    ppd.clearInput();
                    ppd.setTitle(statusInfo);
                }
            }
        });
        ppd.show();
        ppd.showKeyboard();
    }

    private void showFrozenDialog() {
        /** 弹出对话框 */
        final ConfirmDialog confirmDialog = new ConfirmDialog(this, "请找回支付密码", statusInfo, "取消", "找回密码");
        confirmDialog.setCanceledOnTouchOutside(false);
        confirmDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                confirmDialog.dismiss();
            }

            @Override
            public void doRight() {
                jumpToModPayPwd();
                confirmDialog.dismiss();
            }
        });
        confirmDialog.show();
    }

    private void jumpToModPayPwd() {
        PayJumper.jumpToModPwd(this, true);
    }

    @OnClick({
            R.id.btnRechargeWallet,
            R.id.btnRechargePropertyWallet,
            R.id.ibChooseBalance,
            R.id.ibChooseApilay,
            R.id.ibChooseRepeated,
            R.id.ibChooseWeChat,
            R.id.ibChoosePropertyWallet,
            R.id.rlBalancePaidPrice,
            R.id.rlApilayPaidPrice,
            R.id.rlRepeatedlyPaidPrice,
            R.id.rlWeChatPaidPrice,
            R.id.rlPropertyWallet,
            R.id.tvPaid})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnRechargeWallet:/*钱包充值*/
                jumpToRechargeWallet();
                break;
            case R.id.btnRechargePropertyWallet:/*物业钱包充值*/
                jumpToPropertyWalletRecharge();
                break;
            case R.id.tvPaid:/*支付*/
                dataTrackClick("btnPay", null);
                if ((!isPropertyWalletChoose) && (!isApilayChoose) && (!isWalletChoose) && (!isRepeatedChoose) && (!isWeChatChoose)) {
                    ToastHelper.getInstance()._toast("你还未选择支付方式");
                } else {
                    checkPayPwd();
                }
                break;
            case R.id.ibChooseBalance:/*选择支付方式*/
            case R.id.rlBalancePaidPrice:
                ibChooseBalance.setBackgroundResource(R.drawable.icon_selected);
                ibChooseApilay.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseRepeated.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseWeChat.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChoosePropertyWallet.setBackgroundResource(R.drawable.icon_unselected_grey);
                isWalletChoose = true;
                isApilayChoose = false;
                isCreditChoose = false;
                isRepeatedChoose = false;
                isWeChatChoose = false;
                isPropertyWalletChoose = false;
                break;
            case R.id.ibChooseApilay:
            case R.id.rlApilayPaidPrice:
                ibChooseApilay.setBackgroundResource(R.drawable.icon_selected);
                ibChooseBalance.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseRepeated.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseWeChat.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChoosePropertyWallet.setBackgroundResource(R.drawable.icon_unselected_grey);
                isApilayChoose = true;
                isWalletChoose = false;
                isCreditChoose = false;
                isRepeatedChoose = false;
                isWeChatChoose = false;
                isPropertyWalletChoose = false;
                break;
            case R.id.ibChooseRepeated:
            case R.id.rlRepeatedlyPaidPrice:
                ibChooseRepeated.setBackgroundResource(R.drawable.icon_selected);
                ibChooseApilay.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseBalance.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseWeChat.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChoosePropertyWallet.setBackgroundResource(R.drawable.icon_unselected_grey);
                isRepeatedChoose = true;
                isCreditChoose = false;
                isWalletChoose = false;
                isApilayChoose = false;
                isWeChatChoose = false;
                isPropertyWalletChoose = false;
                break;
            case R.id.ibChooseWeChat:
            case R.id.rlWeChatPaidPrice:
                ibChooseWeChat.setBackgroundResource(R.drawable.icon_selected);
                ibChooseRepeated.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseApilay.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseBalance.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChoosePropertyWallet.setBackgroundResource(R.drawable.icon_unselected_grey);
                isWeChatChoose = true;
                isWalletChoose = false;
                isCreditChoose = false;
                isApilayChoose = false;
                isRepeatedChoose = false;
                isPropertyWalletChoose = false;
                break;
            case R.id.rlPropertyWallet:
            case R.id.ibChoosePropertyWallet:
                ibChoosePropertyWallet.setBackgroundResource(R.drawable.icon_selected);
                ibChooseWeChat.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseRepeated.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseApilay.setBackgroundResource(R.drawable.icon_unselected_grey);
                ibChooseBalance.setBackgroundResource(R.drawable.icon_unselected_grey);
                isPropertyWalletChoose = true;
                isWeChatChoose = false;
                isWalletChoose = false;
                isCreditChoose = false;
                isApilayChoose = false;
                isRepeatedChoose = false;
                break;
            default:
                break;
        }
    }

    public void setPaid() {
        Map<String, Object> datamap = new HashMap<>();
        datamap.put("OdrType", orderInfo);
        showDialog();
        initParams(orderInfo, outtradeno, totalCost);
        if (isApilayChoose) {/*支付宝*/
            datamap.put("payChn", "支付宝");
            //getApilayFromServer(handler);
            getNewApilayFromServer(handler);
        } else if (isWalletChoose) {/*钱包支付*/
            datamap.put("payChn", "余额支付");
            requestPayWithWallet();
        } else if (isCreditChoose) {/*积分支付*/
            datamap.put("payChn", "积分支付");
            /**积分不足*/
            if (Integer.parseInt(getTotalCredit()) < Double.parseDouble(totalCost)) {
                DialogHelper.closeDialog(dialog);
                ToastHelper.getInstance()._toast("您的积分不足，暂时不能支付");
            } else {
                List<String> list = new ArrayList<>();
                list.add(orderID);
                Map<String, Object> map = new HashMap<>();
                map.put("orderIDs", list);
                JSONRequest.getInstance().sendRequest(JSONRequest.POST, Constant.URL_ORDER_CREDIT_PAID, map, handler, CREDIT_PAID, HttpUtil.ACTION_JSON);
            }
        } else if (isRepeatedChoose) {/*银联支付(连连)*/
            datamap.put("payChn", "连连支付");
            requestPayWithUnionPay();
        } else if (isWeChatChoose) { /*微信支付*/
            datamap.put("payChn", "微信支付");
            getWeChatFromServer(handler);
        } else if (isPropertyWalletChoose) {
            datamap.put("payChn", "物业缴费钱包支付");
            requestPayWithPropertyWallet();
        }
        dataTrackClick("btnPay", datamap);

    }

    /** 处理可用的支付方式列表 */
    private void handlePayMethod(List<Map<String, Object>> paidMethod) {
        if (Double.parseDouble(totalCost) <= 0) {/*应付总额<0*/
            rlApilayPaidPrice.setVisibility(View.GONE);
            rlRepeatedPaidPrice.setVisibility(View.GONE);
            rlWeChatPaidPrice.setVisibility(View.GONE);
            rlBalancePaidPrice.setVisibility(View.VISIBLE);
        } else {
            for (int i = 0; i < paidMethod.size(); i++) {
                String payMethodCode = String.valueOf(paidMethod.get(i).get("paymentCode"));
                if (payMethodCode.equals(PaymentModule.PAID_CODE[0])) {
                    rlBalancePaidPrice.setVisibility(View.VISIBLE);
                } else if (payMethodCode.equals(PaymentModule.PAID_CODE[1])) {
                    rlRepeatedPaidPrice.setVisibility(View.VISIBLE);
                } else if (payMethodCode.equals(PaymentModule.PAID_CODE[2])) {
                    rlWeChatPaidPrice.setVisibility(View.VISIBLE);
                } else if (payMethodCode.equals(PaymentModule.PAID_CODE[3])) {
                    rlApilayPaidPrice.setVisibility(View.VISIBLE);
                } else if (payMethodCode.equals(PaymentModule.PAID_METHOD_PROPERTY_WALLET)) {
                    rlPropertyWallet.setVisibility(View.VISIBLE);
                    requestPropertyWalletMoney();/*若支持物业缴费钱包支付,则请求其余额*/
                }
            }
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Map<String, Object> map = JSONHelper.jsonToMap(msg.obj.toString());
            switch (msg.what) {
                case PAID_METHOD:/*支付方式*/
                    List<Map<String, Object>> paidMethod = FastJsonTools.getListMap(msg.obj.toString());
                    handlePayMethod(paidMethod);
                    break;
                case CREDIT_PAID:
                    @SuppressWarnings("unchecked")
                    Map<String, Object> mapList = (Map<String, Object>) JSONHelper.jsonToMap(msg.obj.toString()).get(
                            "entity");
                    if (map.get("errCode").toString().equals("0")) {
                        ExitApplication.getInstance().addMainActivity(UsersPaidActivity.this);
                        ToastHelper.getInstance()._toast("积分支付成功");
                        UserSp.setPoint(String.valueOf(mapList.get("score")));
                        mOrderType = "7";
                        skipResult(0);
                    }
                    break;
                case 0:/*钱包支付*/
                    if (map.get("errCode").toString().equals("0")) {
                        ExitApplication.getInstance().addMainActivity(UsersPaidActivity.this);
                        ToastHelper.getInstance()._toast("支付成功");
                        disablePayButton();
                        requestWalletPrice();
                        skipResult(0);
                    } else {
                        skipResult(2);
                    }
                    requestUpdatePropertyOrderStatus();
                    break;
                case PaymentModule.APILAY_KEY:
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(msg.obj.toString());
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    /** 支付宝key */
                    //try {
                    //callBack(getApilayJson(jsonObject));
                    callBack(jsonObject);
                    break;
                //} catch (JSONException e) {
                //    e.printStackTrace();
                //}
                case REPERT_KEY:
                    JSONObject jsonObject2 = null;
                    try {
                        jsonObject2 = new JSONObject(msg.obj.toString());
                        jsonObject2.put("outtradeno", outtradeno);
                        jsonObject2.put("totalCost", totalCost);
                        jsonObject2.put("goodName", orderInfo);
                        jsonObject2.put("phone", phone);
                    } catch (JSONException e1) {
                        e1.printStackTrace();
                    }
                    repeatCallBack(jsonObject2);
                    break;
                case WALLET_BALANCE:
                    String json = (String) msg.obj;
                    Map<String, Object> mapList2 = (Map<String, Object>) JSONHelper.jsonToMap(json).get(
                            "entity");
                    walletBalance = String.valueOf(mapList2.get("money"));
                    setWalletText();
                    break;
                case PaymentModule.WECHAT_KEY:
                    getWeChatJson(msg);
                    break;
                case VOCHER_CANCEL:
                    break;
                case Constant.WHAT_TOKEN_EXPIRED:
                    isLogin(dialog);
                    break;
                case Constant.WHAT_BALANCE_LESS:
                    ToastHelper.getInstance()._toast(
                            getResources().getString(R.string.code_13004));
                    break;
                case Constant.WHAT_ERROR_HTTP:
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    break;
                default:
                    break;
            }
            DialogHelper.closeDialog(dialog);
        }
    };

    private void delSelectedShopCartGoods() {
        ShoppingCartBiz.delGoodsList(products);
    }

    private void skipResult(int result) {
        final Intent intent = new Intent(UsersPaidActivity.this, PaidResultActivity.class);
        intent.putExtra("btnText", getString(R.string.home_return));
        intent.putExtra("orderInfo", tvOrderInfoText.getText().toString());
        intent.putExtra("totalPrice", tvOrderTotalPrice.getText().toString());
        intent.putExtra("repairID", repairID);
        intent.putExtra("orderID", orderID);
        intent.putExtra("orderType", mOrderType);
        intent.putExtra("serviceOrderID", serviceOrderID);
        intent.putExtra("orderList", orderList);
        intent.putExtra("points", points);
//		intent.putExtra("productsID", getIntent().getStringArrayExtra("productsID"));
        ArrayList<String> products = getIntent().getExtras().getStringArrayList("productsID");
        intent.putStringArrayListExtra("productsID", products);
        switch (result) {
            case 0:/**支付成功*/
                if (type.equals(PaymentModule.mode[3])) {
                    intent.putExtra("feeType", feeType);
                }
                intent.putExtra("orderType", mOrderType);
                intent.putExtra("type", type);
                intent.putExtra("info", getString(R.string.paid_success));
                break;
            case 1:/**支付中*/
                if (isRepeatedChoose) {
                    intent.putExtra("padding", getString(R.string.lianlian_paiding));
                } else {
                    intent.putExtra("padding", getString(R.string.apliay_paiding));
                }
                intent.putExtra("btnText", getString(R.string.close));
                intent.putExtra("info", getString(R.string.order_paiding));
                intent.putExtra("isPaiding", true);
                break;
            case 2:/**支付失败*/
                if (isRepeatedChoose) {
                    intent.putExtra("error", getString(R.string.lianlian_paid_failue));
                } else {
                    intent.putExtra("error", getString(R.string.apliay_paid_failue));
                }
                intent.putExtra("btnText", getString(R.string.close));
                intent.putExtra("info", getString(R.string.paid_failue));
                intent.putExtra("isSuccess", false);
                break;
            default:
                break;
        }
        ExitApplication.getInstance().addMainActivity(UsersPaidActivity.this);
        startActivity(intent);
    }

    /** 支付成功后,禁用支付按钮 */
    private void disablePayButton() {
        tvPaid.setEnabled(false);
        tvPaid.setBackgroundResource(R.drawable.shape_btn_gray);
    }

    /**
     * 支付宝回调方法
     *
     * @param jsonObject
     */
    private void callBack(JSONObject jsonObject) {
        initpayFactory();
        IPayManage iPayManage = payFactory.produce("alipay", new IPayCallBack() {
            @Override
            public void success() {
                paySuccess();
            }

            @Override
            public void handling() {
                payHandling();
            }

            @Override
            public void fail() {
                payFail();
            }
        });
        //iPayManage.setParameter(this, jsonObject);
        iPayManage.newPay(this, jsonObject);
    }

    /**
     * 连连支付回调方法
     *
     * @param jsonObject
     */
    private void repeatCallBack(JSONObject jsonObject) {
        initpayFactory();
        IPayManage iPayManage = payFactory.produce("lianlian", new IPayCallBack() {
            @Override
            public void success() {
                paySuccess();
            }

            @Override
            public void handling() {
                payHandling();
            }

            @Override
            public void fail() {
                payFail();
            }
        });
        iPayManage.setParameter(this, jsonObject);
    }

    /**
     * 支付成功
     */
    private void paySuccess() {
        ToastHelper.getInstance()._toast("支付成功");
        disablePayButton();
        skipResult(0);
    }

    /**
     * 支付失败
     */
    private void payFail() {
        ToastHelper.getInstance()._toast("支付失败");
        cancelVoucher(false);
        skipResult(2);
    }

    /**
     * 支付中
     */
    private void payHandling() {
        ToastHelper.getInstance()._toast("支付中");
        disablePayButton();
        skipResult(1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            /**充值成功后，刷新数据*/
            requestWalletPrice();
        }
    }

    public void onBackClick(View v) {
        cancelVoucher(true);
        DataTrack.clickTrack("btnBack", null);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        cancelVoucher(true);
    }

    private void delShopCartItem() {
        ShoppingCartBiz.delGood(productID);
    }

    private void cancelVoucher(boolean isFinish) {
        if (outtradeno != null) {
            String url = null;
            Map<String, Object> map = new HashMap<String, Object>();
            /**缴费调用取消解冻抵用券*/
            if (null != status) {
                if (status.equals("pays")) {
                    url = Constant.URL_VOUCHER_CANCEL;
                    map.put("outtradeno", outtradeno);
                }
            }
            JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, map, handler, VOCHER_CANCEL, HttpUtil.ACTION_URI);
        }
        if (isFinish) {
            finish();
            /*增加动画*/
            IntentHelper.getInstances().jumpActivityAnimation(this, true);
        }
    }

    @Override
    public void getResp(BaseResp resp) {
        if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) {
            paidInfo.setBtnText(getString(R.string.home_return));
            paidInfo.setOrderInfo(orderInfo);
            paidInfo.setTotalPrice(tvOrderTotalPrice.getText().toString());
            paidInfo.setRepairID(repairID);
            paidInfo.setServiceOrderID(serviceOrderID);
            paidInfo.setProductsID(getIntent().getExtras().getStringArrayList("productsID"));
            if (resp.errCode == 0) {
                if (type.equals(PaymentModule.mode[3])) {
                    paidInfo.setFeeType(feeType);
                } else {
                    paidInfo.setFeeType(3);
                }
                paidInfo.setType(type);
                paidInfo.setPaidInfo(getString(R.string.paid_success));
                paidInfo.setIsSuccess(true);
            } else if (resp.errCode == -1 || resp.errCode == -2) {
                if (isRepeatedChoose) {
                    paidInfo.setTvApliayTitle(getString(R.string.lianlian_paid_failue));
                } else {
                    paidInfo.setTvApliayTitle(getString(R.string.apliay_paid_failue));
                }
                paidInfo.setPaidInfo(getString(R.string.paid_failue));
                paidInfo.setBtnText(getString(R.string.close));
                paidInfo.setIsSuccess(false);
            }
            putPaidInfo(paidInfo);
        }
    }
}